<template>
  <div class="bg-[#ECEFF8]">
    <!-- DAMS控制台 -->
    <div v-if="getAppInfo.APP_CODE == 'DAMS'" class="h-full control overflow-y-auto p-2">
      <div v-for="(v, index) in requestData" :key="index" class="w-full mb-3">
        <div class="text-xl font-semibold uppercase">{{ v.machineName }}</div>
        <div class="mb-1 bg-white border rounded flex justify-between py-2 px-3">
          <div class="flex items-center">
            <div class="mr-2"><vui-icon icon="server-fill" /></div>
            <div class="text-xl mr-2 uppercase">{{ v.serverName }}</div>
            <div class="name">{{ v.name }}</div>
            <div class="text-xs mr-8">
              <span>{{ translateTitle('Base.components.操作系统版本号') }} :</span>
              <span class="text-blue-500">{{ v.version }}</span>
            </div>
            <div class="text-xs mr-8">
              <span>CPU :</span>
              <span class="text-blue-500">{{ v.arch }}</span>
            </div>
            <div class="text-xs mr-8">
              <span>{{ translateTitle('Base.components.CPU核心数') }} :</span>
              <span class="text-blue-500">{{ v.availableProcessors }}</span>
            </div>
          </div>
          <div v-if="v.serverInfo" class="flex items-center">
            <el-button plain type="primary" @click="systemReset(v)">
              <vui-icon icon="restart-line" />
              {{ translateTitle('Base.components.重启') }}
            </el-button>
          </div>
        </div>

        <div class="grid grid-cols-4 gap-2">
          <div class="bg-white border rounded echart-data">
            <div class="echart-data-title">{{ translateTitle('Base.components.CPU使用率') }}</div>
            <div class="flex">
              <div class="w-1/2">
                <GaugeProgress
                  :name="translateTitle('Base.components.当前进程CPU使用率')"
                  :progress-num="v.processCpuLoad"
                  :uuid="`processCpuLoad_${index}`"
                />
              </div>
              <div class="w-1/2">
                <GaugeProgress
                  :name="translateTitle('Base.components.物理机CPU使用率')"
                  :progress-num="v.systemCpuLoad"
                  :uuid="`systemCpuLoad_${index}`"
                />
              </div>
            </div>
          </div>
          <div class="bg-white border rounded echart-data relative">
            <div class="echart-data-title">{{ translateTitle('Base.components.物理机内存使用') }}(MB)</div>
            <div>
              <BorderRadius
                type="1"
                :uuid="`memory_${index}`"
                :v1="v.freeSwapSpaceSize"
                :v2="v.totalPhysicalMemorySize"
                :v3="v.freePhysicalMemorySize"
              />
            </div>
          </div>
          <div class="bg-white border rounded echart-data">
            <div class="echart-data-title">{{ translateTitle('Base.components.JVM内存') }}(MB)</div>
            <div>
              <BorderRadius type="2" :uuid="`jvm_${index}`" :v1="v.jvmMaxMemory" :v2="v.jvmTotalMemory" :v3="v.jvmFreeMemory" />
            </div>
          </div>
          <div class="bg-white border rounded echart-data">
            <div class="echart-data-title">{{ translateTitle('Base.components.文件描述符数量') }}</div>
            <div>
              <span class="w-full px-5 text-xs text-gray-700">{{ translateTitle('Base.components.最大文件描述符数量') }}</span>
              <div class="flex items-center mb-4">
                <span class="max-files-num-1"></span>
                <span class="use-files-num use-files-num-1">
                  {{ v.maxFileDescriptorCount }}
                </span>
              </div>
            </div>
            <div>
              <span class="w-full px-5 text-xs text-gray-700">{{ translateTitle('Base.components.已经使用的文件描述符数量') }}</span>
              <div class="flex items-center">
                <span class="max-files-num-2"></span>
                <span class="use-files-num use-files-num-2">
                  {{ v.openFileDescriptorCount }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <div v-if="v.diskInfo && v.diskInfo.length > 0" class="bg-white border rounded mt-2">
          <div class="echart-data-title">{{ translateTitle('Base.components.磁盘占用') }}(GB)</div>
          <div class="grid grid-cols-4 gap-2">
            <div v-for="(vv, i) in v.diskInfo" :key="i" class="chart-type-pie-item">
              <ChartTypePie :data="vv" :uuid="`disk_${index}_${i}`" />
            </div>
          </div>
        </div>
      </div>
      <VuiModal v-show="showResetModal" v-model="showResetModal">
        <template #title>{{ translateTitle('Base.components.提示') }}</template>
        <div class="layer-modal-body flex justify-center overflow-hidden w-[400px] min-h-[160px]">
          <div class="w-4/5">
            <div class="flex justify-center"><img src="~@/assets/dams_images/lock@2x.png" width="40" /></div>
            <div class="flex justify-center text-sm text-gray-800 my-2">{{ translateTitle('Base.components.输入密码以允许此次操作') }}</div>
            <div class="flex justify-center">
              <el-input v-model="systemPassword" :placeholder="translateTitle('Base.components.请输入密码')" type="password" />
            </div>
          </div>
        </div>
        <template #footer>
          <div class="flex justify-center p-3 border-t border-gray-100">
            <el-button @click="showResetModal = false">{{ translateTitle('Base.components.取消') }}</el-button>
            <el-button :loading="resetBtnLoading" type="primary" @click="restartBtn">{{ translateTitle('Base.components.确认') }}</el-button>
          </div>
        </template>
      </VuiModal>
    </div>

    <!-- 其它系统控制台 -->
    <div v-else class="index-container" :style="{ 'background-image': `url(${backgroundUrl})`, 'background-size': 'cover' }"></div>
  </div>
</template>

<script>
  import { defineComponent } from 'vue'
  import debounce from 'lodash/debounce'
  import { getList } from '@/project/dams/api/home'
  import { GFCD } from '@/utils/utils'
  import GaugeProgress from './homeComponents/gaugeProgress.vue'
  import BorderRadius from './homeComponents/borderRadius.vue'
  import ChartTypePie from './homeComponents/chartTypePie.vue'
  import { translateTitle } from '@/utils/i18n'
  import request from '@/utils/request'
  import cloneDeep from 'lodash/cloneDeep'

  export default defineComponent({
    name: 'HomePc',
    components: { GaugeProgress, BorderRadius, ChartTypePie },
    data() {
      return {
        clientHeight: 400,
        requestData: [],
        showResetModal: false,
        resetBtnLoading: false,
        systemInfo: {},
        systemPassword: '',
        backgroundUrl: '',
      }
    },
    computed: {
      getAppInfo() {
        return this.$store.getters['user/getAppInfo']
      },
      appCode() {
        return this.$store.getters['user/appCode']
      },
    },
    created() {
      if (process.env.VUE_APP_BuildProject === 'pda') {
        this.$router.push('/menu')
        return
      }
      if (this.appCode != 'DAMS') return
      this.getData()
    },
    mounted() {
      this.windowResize()
      window.addEventListener('resize', this.windowResize)
      if (this.appCode != 'DAMS') {
        this.getImg()
        return
      }
      setInterval(this.getData, 5 * 1000)
    },
    methods: {
      async getImg() {
        console.log('getImg=======', cloneDeep(this.getAppInfo))
        const url = GFCD('dams')
        if (!this.getAppInfo.BACKGROUND_IMAGE_BASE64) return
        let res = await request({
          url: `${url.domain}${url.baseUrl}`,
          method: 'post',
          data: {
            data: JSON.stringify({ FILE_SEQ: this.getAppInfo.BACKGROUND_IMAGE_BASE64, '#OUTPUT_TYPE#': 'base64' }),
            method: 'dams.file.common.download',
          },
          // responseType: 'blob',
        })
        console.log(res)
        this.backgroundUrl = `data:image/${res.data[0].FILE_SUFFIX};base64,${res.data[0].BASE64_STRING}`
      },
      translateTitle,
      //小数乘法精度丢失
      floatMultiply(arg1, arg2) {
        if (arg1 == null || arg2 == null) {
          return null
        }
        var n1, n2
        var r1, r2 // 小数位数
        try {
          r1 = arg1.toString().split('.')[1].length
        } catch (e) {
          r1 = 0
        }
        try {
          r2 = arg2.toString().split('.')[1].length
        } catch (e) {
          r2 = 0
        }
        n1 = Number(arg1.toString().replace('.', ''))
        n2 = Number(arg2.toString().replace('.', ''))
        return (n1 * n2) / Math.pow(10, r1 + r2)
      },
      getData() {
        const url = GFCD('dams')
        getList(`${url.domain}${url.baseUrl}`, {
          data: '{}',
          method: 'dams.query.system.monitor.info',
        }).then((res) => {
          let list = []
          const dataObj = JSON.parse(res.data)
          if (res.data != '{}') {
            for (const key in dataObj) {
              const element = JSON.parse(dataObj[key])

              list.push({ machineName: key.split(':')[0], serverName: key.split(':')[1], ...element })
            }

            const keys = ['availableProcessors', 'maxFileDescriptorCount', 'openFileDescriptorCount']
            list.forEach((row) => {
              for (const key in row) {
                const element = row[key]
                if (typeof element == 'number' && element > 1 && keys.indexOf(key) == -1) {
                  row[key] = Math.floor((element / 1024 / 1024) * 100) / 100
                }
                if (typeof element == 'number' && element < 1 && keys.indexOf(key) == -1) {
                  row[key] = this.floatMultiply(Math.floor(element * 10000) / 10000, 100)
                }
              }
            })
            this.requestData = list
          }
        })
      },
      windowResize: debounce(function () {
        this.clientHeight = document.documentElement.clientHeight - 34 - 16 - 10
      }, 100),
      systemReset(item) {
        this.showResetModal = true
        this.systemInfo = item
      },
      getCallHttpAddress(data, openMessage = true) {
        return request({
          url: this.systemInfo.serverInfo.callHttpAddress,
          method: 'post',
          data: {
            data: JSON.stringify(data),
            method: '*.app.end.point',
          },
          notOpenMessage: !openMessage,
        })
      },
      restartBtn() {
        if (this.systemPassword == '') {
          this.$baseMessage(translateTitle('Base.components.请输入密码'), 'warning')
          return
        }

        this.getCallHttpAddress(
          {
            password: this.systemPassword,
            action: 'reload',
          },
          true
        )
          .then((data) => {
            if (data.code === '00000') {
              this.$baseMessage(data.msg, 'success')
              this.$baseLoading(null, translateTitle('Base.components.重启中'))
              this.restartComplete()
            }
          })
          .catch((e) => {
            console.log('重启失败', e)
          })
      },
      restartComplete() {
        this.getCallHttpAddress({}, false)
          .then(() => {
            location.reload()
          })
          .catch(() => {
            setTimeout(() => {
              this.restartComplete()
            }, 2000)
          })
      },
    },
  })
</script>

<style lang="scss" scoped>
  .index-container {
    background-size: 100% 100%;
    background-position: bottom;
    background-repeat: no-repeat;
    position: relative;
    width: 100%;
    height: 100vh;
  }
  .control {
    height: calc(100vh - 70px);
  }
  .el-tag {
    height: 44px;
    line-height: 20px;
    width: 47%;
    margin-bottom: 10px;
    text-align: center;
  }
  .name {
    background: rgba(50, 112, 255, 0.1);
    border: 1px solid #3270ff;
    border-radius: 14px;
    padding: 3px 10px;
    font-size: 12px;
    margin-right: 20px;
  }
  .echart-data {
    min-height: 100px;
  }
  .echart-data-title {
    margin: 10px 0;
    padding: 0 10px;
    border-left: 4px solid #3270ff;
  }
  .max-files-num-1 {
    height: 10px;
    background: linear-gradient(270deg, #3270ff, #fff 81%);
    border-radius: 4px;
    display: block;
    width: 100%;
  }
  .max-files-num-2 {
    height: 10px;
    background: linear-gradient(270deg, #fea728, #fff 81%);
    border-radius: 4px;
    display: block;
    width: 100%;
  }
  .use-files-num {
    width: 100px;
    font-weight: 700;
    text-align: left;
    padding-left: 10px;
  }
  .use-files-num-1 {
    color: #3270ff;
  }
  .use-files-num-2 {
    color: #fea728;
  }
</style>
